package ldh.maker.component;

import javafx.application.Platform;
import javafx.scene.control.TextArea;
import javafx.scene.control.TreeItem;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import ldh.maker.code.CreateCode;
import ldh.maker.db.SettingDb;
import ldh.maker.util.DbInfoFactory;
import ldh.maker.util.FileUtil;
import ldh.maker.vo.SettingData;
import ldh.maker.vo.TreeNode;
import org.fxmisc.flowless.VirtualizedScrollPane;
import org.fxmisc.richtext.CodeArea;
import org.fxmisc.richtext.LineNumberFactory;
import org.fxmisc.richtext.model.StyleSpans;
import org.fxmisc.richtext.model.StyleSpansBuilder;

import java.io.File;
import java.util.Collection;
import java.util.Collections;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by ldh on 2017/4/2.
 */
public class CodePane extends VBox {

    private CodeTextArea codeTextArea = new CodeTextArea(false);

    public CodePane(TreeItem<TreeNode> treeItem, String javaName, String pack, CreateCode createCode) {
        codeTextArea.setEditable(false);
//        codeTextArea.replaceText(0, 0, sampleCode);

        this.getChildren().addAll(codeTextArea);
        this.setSpacing(10d);
        VBox.setVgrow(new VirtualizedScrollPane<>(codeTextArea), Priority.ALWAYS);

        loadData(treeItem, javaName, pack, createCode);
    }

    public void loadData(TreeItem<TreeNode> treeItem, String javaName, String pack, CreateCode createCode) {
        new Thread(() -> {
            String root = FileUtil.getSourceRoot();
            String file = root + "/code/" + treeItem.getParent().getParent().getParent().getValue().getText();
            file = file + "/" + getDir(createCode);
            try {
                String t = pack.replace(".", "/");
                file = file + "/" + t + "/" + javaName;
                File f = new File(file);
                if (!f.exists()) return;
                String code = FileUtil.loadFile(file);
                Platform.runLater(() -> {
                    codeTextArea.replaceText(0, 0, code);
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    protected String getDir(CreateCode createCode) {
        return createCode.getProjectName() + "/src/main/java";
    }
}
